package com.itheima.health.service.consumer;

import com.itheima.health.common.RedisConst;
import com.itheima.health.common.RocketMqConst;
import com.itheima.health.entity.SmsTask;
import com.itheima.health.utils.SmsSendUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RocketMQMessageListener(topic = RocketMqConst.TOPIC_SMS_SEND, consumerGroup = "sms-send-consumer")
public  class SmsSendConsumer implements RocketMQListener<SmsTask> {


    @Autowired
    private RedisTemplate redisTemplate;

    public void onMessage(SmsTask smsTask) {
        log.info("[短信发送消费者]received message: {}", smsTask);
        log.info("[短信发送消费者-发送中]");

        try { //让他睡 我们看返回结果
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + smsTask.getType() + ":" + smsTask.getTelephone();
        //第四次到第六次
        if (smsTask.getCount() > 4 && smsTask.getCount() <= 8) {
            //从redis获取
            String redisCode = (String) redisTemplate.boundValueOps(redisKey).get();

            if (!StringUtils.isEmpty(redisCode)) {
                SmsSendUtils.smsSend(redisCode, smsTask.getTelephone(), smsTask.getType());
                log.info("[短信发送消费者-发送成功]code：{}，phone：{}，type：{}", redisCode, smsTask.getTelephone(), smsTask.getType());
            } else {
                int codeTimeOut = (int) (1000 + new SecureRandom().nextDouble() * 8999);
                redisTemplate.boundValueOps(redisKey).set(String.valueOf(codeTimeOut), 3 * 60L, TimeUnit.SECONDS);
                SmsSendUtils.smsSend(String.valueOf(codeTimeOut), smsTask.getTelephone(), smsTask.getType());
                log.info("[短信发送消费者-发送成功]codeTimeOut：{}，phone：{}，type：{}", codeTimeOut, smsTask.getTelephone(), smsTask.getType());
            }
        } else {
            int code = (int) (1000 + new SecureRandom().nextDouble() * 8999);
            //保存验证码 redis
            redisTemplate.boundValueOps(redisKey).set(String.valueOf(code), 3 * 60L, TimeUnit.SECONDS);
            log.info("[短信发送消费者-正常发送成功]code：{}，phone：{}，type：{}", code, smsTask.getTelephone(), smsTask.getType());
            SmsSendUtils.smsSend(String.valueOf(code), smsTask.getTelephone(), smsTask.getType());
        }
    }
}